package ssau.knyazev.cafe.gui.components;

import java.awt.Component;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

import ssau.knyazev.cafe.model.Dish;
import ssau.knyazev.cafe.model.OrderRecord;
import ssau.knyazev.common.UniException;


public class OrderRecordTable extends JTable{

	private static final long serialVersionUID = -6650100341471697513L;

	public OrderRecordTable(){
	}
	
	private class OrderEditor extends DefaultCellEditor{

		public OrderEditor(JComboBox comboBox){
			super(comboBox);
		}
		
		public OrderEditor(JTextField textField){
			super(textField);
		}

		private static final long serialVersionUID = 8071778868462800493L;
		
	}
	
	private class OrderRender extends DefaultTableCellRenderer{

		private static final long serialVersionUID = 4110210860738440200L;
		
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus,
				int row, int column) {
			if (isSelected) {
	            setForeground(table.getSelectionForeground());
	            super.setBackground(table.getSelectionBackground());
	        } else {
	            setForeground(table.getForeground());
	            setBackground(table.getBackground());
	        }
			OrderRecord or = (OrderRecord) value;
			if (column == 0){
				setText(or.getDishName());
			} else {
				setText(or.getCount());
			}
			return this;
		}
		
	}
	
	@Override
	public TableCellRenderer getCellRenderer(int row, int column) {
		return new OrderRender();
	}
	
	@Override
	public TableCellEditor getCellEditor(int row, int column) {
		if (column == 0){
			try {
				cellEditor = new OrderEditor(new JComboBox(loadDishes()));
			} catch (UniException e) {
				e.printStackTrace();
			}
		} else {
			OrderRecord or = (OrderRecord) getValueAt(row, column);
			cellEditor = new OrderEditor(new JTextField(or.getCount()));
		}
		return cellEditor;
	}
	
	@Override
	public boolean isCellEditable(int row, int column) {
		if (column == 0 && getValueAt(row, column) != null)
			return false;
		return true;
	}
	
	private Dish[] loadDishes() throws UniException{
		List<Dish> temp = Dish.loadAll();
		Dish[] dishes = new Dish[temp.size()];
		int i = 0;
		for (Dish x: temp){
			dishes[i] = x;
			i++;
		}
		return dishes;
	}
	
	
	
}
